﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using UtilZ.Dotnet.Ex.Base;
using UtilZ.Dotnet.Ex.Log;
using UtilZ.Dotnet.WindowsDesktopEx.Winform.Base;

namespace LinuxSourcePkDownlader
{
    public partial class FMain : Form
    {
        public FMain()
        {
            InitializeComponent();
        }

        private void FMain_Load(object sender, EventArgs e)
        {
            try
            {
                var redirectAppenderToUI = (RedirectAppender)Loger.GetAppenderByName(null, "RedirectToUI");
                if (redirectAppenderToUI != null)
                {
                    redirectAppenderToUI.RedirectOuput += RedirectLogOutput;
                }

                btnDownload.Text = "开始";
                this.checkBoxLockLog.Checked = logControl.IsLock;
                this.checkBoxLockLog.CheckedChanged += new System.EventHandler(this.checkBoxLockLog_CheckedChanged);


                var list = new List<IPkDownlader>();
                var types = typeof(FMain).Assembly.GetTypes();
                foreach (var type in types)
                {
                    if (!type.IsClass ||
                        type.IsAbstract ||
                        type.GetInterface(typeof(IPkDownlader).FullName) == null)
                    {
                        continue;
                    }

                    list.Add((IPkDownlader)Activator.CreateInstance(type));
                }
                DropdownBoxHelper.BindingIEnumerableGenericToComboBox(comboBoxTargets, list, nameof(IPkDownlader.Name), list.FirstOrDefault());

                //txtDir.Text = @"D:\KylinGFBServerPks";
                txtDir.Text = @"D:\KylinGFBDesktopPks";
                Loger.Info("就绪...");
            }
            catch (Exception ex)
            {
                Loger.Error(ex);
            }
        }

        private void RedirectLogOutput(object sender, RedirectOuputArgs e)
        {
            logControl.AddLog(e.Item.Content, e.Item.Level);
        }

        private void checkBoxLockLog_CheckedChanged(object sender, EventArgs e)
        {
            logControl.IsLock = this.checkBoxLockLog.Checked;
        }

        private void btnClearLog_Click(object sender, EventArgs e)
        {
            logControl.Clear();
        }


        private void btnChioceDir_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            if (fbd.ShowDialog() == DialogResult.OK)
            {
                txtDir.Text = fbd.SelectedPath;
            }
        }

        private ThreadEx _downloadThread = null;
        private string _dir;
        private void btnDownload_Click(object sender, EventArgs e)
        {
            try
            {
                if (this._downloadThread == null)
                {
                    this._downloadThread = new ThreadEx((p) =>
                    {
                        try
                        {
                            IPkDownlader pkDownlader = (IPkDownlader)p.Para;
                            Loger.Info($"{pkDownlader.Name}下载开始...");
                            pkDownlader.Download(p, this._dir);

                            this.Invoke(new Action(() =>
                            {
                                btnDownload.Text = "开始";
                            }));

                            if (p.Token.IsCancellationRequested)
                            {
                                Loger.Info("下载取消...");
                            }
                            else
                            {
                                Loger.Info("下载完成...");
                            }
                        }
                        catch (Exception ex)
                        {
                            Loger.Error(ex, "下载异常...");
                        }
                    }, "下载线程", true);
                }

                if (this._downloadThread.IsRuning)
                {
                    this._downloadThread.Stop();
                }
                else
                {
                    IPkDownlader pkDownlader = DropdownBoxHelper.GetGenericFromComboBox<IPkDownlader>(comboBoxTargets);
                    if (pkDownlader == null)
                    {
                        Loger.Info("无效的下载器...");
                        return;
                    }

                    string dir = txtDir.Text.Trim();
                    if (string.IsNullOrEmpty(dir))
                    {
                        Loger.Info("存放位置不能为空...");
                        return;
                    }
                    dir = Path.GetFullPath(dir);
                    DirectoryInfoEx.CheckDirectory(dir);
                    this._dir = dir;

                    this._downloadThread.Start(pkDownlader);
                    btnDownload.Text = "停止";
                }
            }
            catch (Exception ex)
            {
                Loger.Error(ex);
            }
        }


    }
}
